//
//  NetWorkTool.swift
//  AFNetworking封装
//
//  Created by maker on 2016/11/11.
//  Copyright © 2016年 maker. All rights reserved.
//

import AFNetworking

enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}
class NetWorkTool: AFHTTPSessionManager {
    //let 是线程安全的
    static let shareInstance : NetWorkTool = {
        let tool = NetWorkTool()
        tool.requestSerializer = AFHTTPRequestSerializer()
        
        tool.responseSerializer = AFJSONResponseSerializer()
        tool.responseSerializer.acceptableContentTypes?.insert("application/json")
        tool.responseSerializer.acceptableContentTypes?.insert("text/json")
        tool.responseSerializer.acceptableContentTypes?.insert("text/JavaScript")
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tool
    }()
}

//MARK:==========封装网络请求==========
extension NetWorkTool {
    func request(_ Method:RequestType,URL : String,Params : [String:AnyObject],Result : @escaping (_ result : AnyObject?,_ error : NSError?) -> ()) {
        //1.定义一个成功的闭包
        let successCallBack = { (task : URLSessionDataTask, result : AnyObject?) in
            Result(result, nil)
        }
        
        //2.定义一个失败的闭包
        let failCallBack = { (task : URLSessionDataTask?, error : NSError) in
            Result(nil, error)
        }
        
        
        if Method == .GET {
            
            get(URL, parameters: Params, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failCallBack as? (URLSessionDataTask?, Error) -> Void )
            
        } else {
            
            post(URL, parameters: Params, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failCallBack as? (URLSessionDataTask?, Error) -> Void)
        }
    }
}

//MARK:==========获取 accesstoken==========
extension NetWorkTool {
    func getToken(_ code:String,finished : @escaping (_ result : [String:AnyObject]?,_ error :Error?) -> ()){
        //1.url
        let url = "https://api.weibo.com/oauth2/access_token"
        
        //2.参数
        let params = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        //3.发送网络请求
        request(.POST, URL: url, Params: params as [String : AnyObject]) { (result, error) in
            finished(result as? [String:AnyObject], error)
        }
    }
    
}

//MARK:==========获取用户信息==========
extension NetWorkTool{
    func getUserInfo(_ token:String,uid:String,finished:@escaping (_ result:[String:AnyObject]?,_ error:Error?) -> ()) {
        //1.URL
        let url  = "https://api.weibo.com/2/users/show.json"
        
        request(.GET, URL: url, Params: ["access_token":token as AnyObject,"uid":uid as AnyObject]) { (result, error) in
            finished(result as? [String:AnyObject] , error)
        }
    }
}

//MARK:==========获取首页数据==========
extension NetWorkTool{
    
    func getHomeData(_ since_id:Int,max_id:Int, finised:@escaping (_ result:[[String:AnyObject]]?,_ error:Error?) -> Void) {
        //1.url
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //2.参数
        guard let token = UserInfoViewModel.shareInstance.user?.access_token else {
            return
        }
        let params = ["access_token":token,"since_id":"\(since_id)","max_id":"\(max_id)"]
        
        //3.网络请求
        request(.GET, URL: url, Params: params as [String : AnyObject]) { (result, error) in
            guard let resultDic = result as? [String : AnyObject] else{
                finised(nil, error)
                return
            }
            finised(resultDic["statuses"] as? [[String:AnyObject]], error)
        }
    }
}

//MARK:==========发送文字微博==========
extension NetWorkTool {
    func sendStatus(_ statusStr : String,isSucess:@escaping (_ isSuccess : Bool) -> ()) {
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        let param = ["access_token":(UserInfoViewModel.shareInstance.user?.access_token)!,"status":statusStr]
        
        request(.POST, URL: url, Params: param as [String : AnyObject]) { (result, error) in
            if result != nil{
                isSucess(true)
            }else{
                print(error)
                isSucess(false)
            }
        }
    }
}

//MARK:==========发送带图片的微博==========
extension NetWorkTool {
    func sendImageStaus(_ statusStr : String,image:UIImage,isSucess:@escaping (_ isSuccess : Bool) -> ()) {
        let url = "https://api.weibo.com/2/statuses/upload.json"
        
        let param = ["access_token":(UserInfoViewModel.shareInstance.user?.access_token)!,"status":statusStr]
        
        post(url, parameters: param, constructingBodyWith: { (formData) in
            //拼接appendPartWithFileData(data: NSData, name: String, fileName: String, mimeType: String)
            if let data = UIImageJPEGRepresentation(image, 0.5){
                formData.appendPart(withFileData: data,name : "pic",fileName: "testPic",mimeType:"image/png")
            }
            
            }, progress: nil, success: { (_, _) in
                isSucess(true)
            }) { (_, error) in
                isSucess(false)
                print(error)
        }

    }
}











